package com.lhz.framework.aspect.param;

import com.lhz.common.constant.ResponseState;
import com.lhz.framework.exception.ServiceException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/9/4App 22:34
 * @Description:
 **/
@Component
@Aspect
public class ParameterValidAspect {

    @Before("@annotation(paramValid)")
    public void paramValid(JoinPoint point, ParamValid paramValid) {
        Object[] paramObj = point.getArgs();
        for (Object obj : paramObj) {
            if (obj instanceof BindingResult result) {
                if (result.hasErrors()) {
                    //取第一个作为错误返回
                    throw new ServiceException(ResponseState.VALID_FAIL.getCode(), result.getAllErrors().get(0).getDefaultMessage());
                    /*
                    装载为集合
                    List<ObjectError> allErrors = result.getAllErrors();
                    List<String> lists = new ArrayList<>();
                    for (ObjectError objectError : allErrors) {
                        lists.add(objectError.getDefaultMessage());
                    }*/

                    //统一返回错误
                    //throw new ServiceException(ResponseState.VALID_FAIL);
                }
            }
        }
    }
}
